package com.lh.ruuner;

import com.lh.domian.entity.Article;
import com.lh.mapper.ArticleMapper;
import com.lh.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 将文章浏览数先全查出来 存储到redis中
 *
 * @Author LuoHang
 * @Date 2022-08-31 16:03
 **/
@Component
public class MyRunnerPre implements CommandLineRunner {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询博客信息 id viewCount
        List<Article> articles = articleMapper.selectList(null);
        //存储到redis中
        Map<String, Integer> viewCountMap = articles
                .stream()
                .collect(Collectors.toMap(article-> String.valueOf(article.getId()),
                        article -> Math.toIntExact(article.getViewCount())));
        redisCache.setCacheMap("article:viewCount", viewCountMap);
    }
}
